<script setup lang="ts">
  import { ref, watch } from 'vue';
  import { Modal, Message } from '@arco-design/web-vue';
  import TableLayout from '@/layout/table-layout.vue';
  import { usePageTable } from '@/hooks/arco/usePageTable';
  import { useForm } from '@/hooks/arco/useForm';
  import DetailsDrawer from '@/components/details-drawer/index.vue';
  import * as Lodash from 'lodash';
  import {
    queryInstPositions,
    createPosition,
    updatePosition,
    deletePosition,
  } from '@/api/structure-management/position';
  import { zipData } from '@/views/lhj-v1/util';

  const loading = ref(false);
  const baseNameMap = {
    itemID: { key: 'id', label: '岗位ID' },
    itemName: { key: 'name', label: '岗位名称' },
    itemParentID: { key: 'parentId', label: '上级部门' },
    itemNum: { key: 'staffCount', label: '岗位人数' },
    createAt: { key: 'createdAt', label: '创建时间' },
    btnAction: { label: '操作' },
    btnLook: { label: '查看' },
  };

  // 模态框默认配置
  const modalConfig = {
    title: '提示',
    bodyStyle: 'text-align: center;',
  };

  // 模态框
  const dataModal = ref({
    visible: false,
    type: '',
    title: '',
    cancelBtnText: '取消',
    okBtnText: '保存',
  });

  // 查询表格列配置
  const tableColumns = [
    {
      title: baseNameMap.itemID.label,
      dataIndex: baseNameMap.itemID.key,
      // minWidth: 120,
    },
    {
      title: baseNameMap.itemName.label,
      dataIndex: baseNameMap.itemName.key,
      // minWidth: 200,
    },
    {
      title: baseNameMap.itemNum.label,
      dataIndex: baseNameMap.itemNum.key,
      // minWidth: 100,
    },
    {
      title: baseNameMap.createAt.label,
      dataIndex: baseNameMap.createAt.key,
      // minWidth: 300,
    },
    {
      title: baseNameMap.btnAction.label,
      align: 'center' as const,
      dataIndex: 'action',
      slotName: 'action',
      fixed: 'right',
      width: 100,
    },
  ];

  const pageTable = usePageTable({
    searchForm: {
      state: {
        [baseNameMap.itemName.key]: '',
      },
    },
    table: {
      rowKey: baseNameMap.itemID.key,
      fakePage: true,
      apiFun: async (query) => {
        return queryInstPositions(query[baseNameMap.itemName.key]);
      },
      onSuccess(data) {
        // dataDepartments.value = getDepartmentList(data);
      },
      columns: tableColumns,
    },
  });

  const modalForm = useForm({
    state: {
      [baseNameMap.itemID.key]: '',
      [baseNameMap.itemName.key]: '',
      [baseNameMap.itemParentID.key]: '',
    },
    rules: {
      [baseNameMap.itemID.key]: {
        required: false,
      },
      [baseNameMap.itemName.key]: {
        required: true,
        message: `请输入${baseNameMap.itemName.label}`,
      },
    },
  });

  const drawerHandler = ref({
    props: {
      visible: false,
      raw: {} as any,
      data: {} as any,
      title: '岗位详情',
      deleteText: '确定删除该岗位吗？',
      deleteDesc: '提示：此岗位下的员工需要被重新分配新的岗位。',
      deleteApi: deletePosition,
    },
    showDrawer: (item: any) => {
      console.log('show pos:', item);
      drawerHandler.value.props.visible = true;
      drawerHandler.value.props.raw = item;
      drawerHandler.value.props.data = zipData(item, [
        baseNameMap.itemID,
        baseNameMap.itemName,
        baseNameMap.itemNum,
        baseNameMap.createAt,
      ]);
      console.log(drawerHandler.value.props);
    },
    onDelete: () => {
      pageTable.reload();
    },
    onEdit: (item: any) => {
      modalForm.state[baseNameMap.itemID.key] = item.id;
      modalForm.state[baseNameMap.itemName.key] = item.name;
      modalForm.state[baseNameMap.itemParentID.key] = item.parentId;
      dataModal.value.type = 'edit';
    },
  });

  const handleModalOk = () => {
    // console.log('modalForm:', modalForm.state);
    modalForm
      .validate()
      .then(() => {
        loading.value = true;
        // let modalContent = '确认新增岗位？';
        let messageText = '新增成功！';
        let apiFunc: any = createPosition;
        const jsonData: any = Lodash.cloneDeep(modalForm.state);
        if (dataModal.value.type === 'edit') {
          // modalContent = '确认保存岗位信息？';
          messageText = '保存成功！';
          apiFunc = updatePosition;
        } else if (dataModal.value.type === 'add') {
          // jsonData.ll = '';
        } else {
          return;
        }
        if (jsonData.area && jsonData.area.length >= 3) {
          const [provinceCode, cityCode, districtCode] = jsonData.area;
          jsonData.provinceCode = provinceCode;
          jsonData.cityCode = cityCode;
          jsonData.districtCode = districtCode;
        }
        if (!apiFunc) return;
        apiFunc(jsonData)
          .then(() => {
            dataModal.value.type = '';
            Message.success(messageText);
            pageTable.reload();
          })
          .finally(() => {
            loading.value = false;
          });
        // [zxj:update] 按要求删除
        // Modal.confirm({
        //   ...modalConfig,
        //   content: modalContent,
        //   onOk: (e) =>{
        //     if (!apiFunc) return;
        //     apiFunc(jsonData).then(()=>{
        //       dataModal.value.type = '';
        //       Message.success(messageText);
        //       pageTable.reload();
        //     }).finally(()=>{
        //       loading.value = false;
        //     })
        //   },
        //   onCancel(e) {
        //     loading.value = false;
        //   },
        // });
      })
      .catch((err) => {
        console.error(err);
      });
  };

  watch(
    () => dataModal.value.type,
    (newVal) => {
      switch (newVal) {
        case 'add': {
          dataModal.value.title = '新增岗位';
          modalForm.state[baseNameMap.itemName.key] = '';
          modalForm.state[baseNameMap.itemParentID.key] = '';
          break;
        }
        case 'edit': {
          dataModal.value.title = '编辑岗位';
          break;
        }
        default:
          dataModal.value.visible = false;
          return;
      }
      dataModal.value.visible = true;
    }
  );
</script>

<template>
  <div class="m-position">
    <TableLayout v-bind="pageTable.bindProps" @create="dataModal.type = 'add'">
      <template #searchForm="{ state }">
        <a-form-item
          :field="baseNameMap.itemName.key"
          :label="baseNameMap.itemName.label"
        >
          <a-input
            v-model="state[baseNameMap.itemName.key]"
            :placeholder="'请输入' + baseNameMap.itemName.label"
            allow-clear
          />
        </a-form-item>
      </template>
      <template #action="{ record }">
        <a-space>
          <a-button
            size="small"
            type="text"
            @click="drawerHandler.showDrawer(record)"
            >{{ baseNameMap.btnLook.label }}</a-button
          >
        </a-space>
      </template>
    </TableLayout>
    <!-- 详情 drawer -->
    <DetailsDrawer
      v-bind="drawerHandler.props"
      @cancel="drawerHandler.props.visible = false"
      @delete="drawerHandler.onDelete"
      @edit="drawerHandler.onEdit"
    />
    <!-- 新增/编辑 Modal -->
    <div class="m-department-modal">
      <a-modal
        v-model:visible="dataModal.visible"
        top="20%"
        :align-center="false"
        @cancel="dataModal.type = ''"
      >
        <template #title>{{ dataModal.title }}</template>
        <a-form v-bind="modalForm.bindProps" layout="vertical">
          <a-form-item
            style="margin-bottom: 0"
            :field="baseNameMap.itemName.key"
            :label="baseNameMap.itemName.label"
            required
          >
            <a-input
              v-model="modalForm.state[baseNameMap.itemName.key]"
              :placeholder="'请输入' + baseNameMap.itemName.label"
            />
          </a-form-item>
        </a-form>
        <template #footer>
          <ae-button purpose="cancel" @click="dataModal.type = ''">{{
            dataModal.cancelBtnText
          }}</ae-button>
          <ae-button purpose="save" :loading="loading" @click="handleModalOk">{{
            dataModal.okBtnText
          }}</ae-button>
        </template>
      </a-modal>
    </div>
  </div>
</template>

<style lang="less" scoped></style>
